<%
   new_prefix = sprintf("%s%s%s", prefix, prefix.empty? ? "" : "_", property.out_name)
   func_def = sprintf("flatten_%s(d, array_index, current_value, exclude_output):", new_prefix)
   if (func_def.length + 4) > 79
     spaces = sprintf("def flatten_%s(", new_prefix).length
     func_def = sprintf("flatten_%s(d, array_index,\n%scurrent_value, exclude_output):", new_prefix, ' ' * spaces)
   end
-%>
<% if !property.from_response.nil? -%>


def <%= func_def %>
<%= indent(lines(property.from_response), 4) -%>
<% elsif property.is_a?(Api::Type::Array) && property.item_type.is_a?(Api::Type::NestedObject) -%>


def <%= func_def %>
    n = 0
    result = current_value
    has_init_value = True
    if result:
        n = len(result)
    else:
        has_init_value = False
        result = []
<%   if property.crud.include?("r") -%>
        v = navigate_value(d, [<%= index2navigate(property.field) %>],
                           array_index)
        if not v:
            return current_value
        n = len(v)
<%   else -%>
<%     raise "check this case and remove me to go on!!!" -%>
        n = 1
<%   end -%>

    new_ai = dict()
    if array_index:
        new_ai.update(array_index)

    for i in range(n):
        new_ai["<%= property.field %>"] = i

        val = dict()
        if len(result) >= (i + 1) and result[i]:
            val = result[i]
<%   nested_properties = nested_properties(property) -%>
<%   nested_properties.each do |prop| -%>

<%= convert_resp_parameter(prop, "d, new_ai", new_prefix, "val", 8) %>
<%   end -%>

        if len(result) >= (i + 1):
            result[i] = val
        else:
            for _, v in val.items():
                if v is not None:
                    result.append(val)
                    break

    return result if (has_init_value or result) else current_value
<%   nested_properties.each do |prop| -%>
<%     next unless has_readable_property(prop) -%>
<%= lines(build_flatten_method(new_prefix, prop)) -%>
<%   end -%>
<% elsif property.is_a?(Api::Type::NestedObject) -%>


def <%= func_def %>
    result = current_value
    has_init_value = True
    if not result:
        result = dict()
        has_init_value = False
<%   nested_properties = nested_properties(property) -%>
<%   nested_properties.each do |prop| -%>

<%= convert_resp_parameter(prop, "d, array_index", new_prefix, "result", 4) %>
<%   end -%>

    if has_init_value:
        return result

    for _, v in result.items():
        if v is not None:
            return result
    return current_value
<%   nested_properties.each do |prop| -%>
<%     next unless has_readable_property(prop) -%>
<%= lines(build_flatten_method(new_prefix, prop)) -%>
<%   end -%>
<% end # if property.is_a?(Api::Type::Array) -%>
